package com.dlc.beijingrfid.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import com.bumptech.glide.Glide;
import com.dlc.commonlibrary.dialog.UpdateDialog;
import com.dlc.commonlibrary.utils.DataCleanManager;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.commonlibrary.utils.glide.transform.BlurTransform;
import com.dlc.commonlibrary.utils.glide.transform.CircleTransform;
import com.dlc.commonlibrary.widget.CommonItemView;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.beijingrfid.R;
import com.dlc.beijingrfid.activity.AboutWeActivity;
import com.dlc.beijingrfid.activity.ForgetPasswordActivity;
import com.dlc.beijingrfid.activity.MessageActivity;
import com.dlc.beijingrfid.activity.OpinionFeedbackActivity;
import com.dlc.beijingrfid.activity.SettingActivity;
import com.dlc.beijingrfid.base.BaseFragment;
import com.dlc.beijingrfid.helper.UpdateAppHttpUtil;
import com.dlc.beijingrfid.helper.UserHelper;
import com.dlc.beijingrfid.net.NetConstants;
import com.dlc.beijingrfid.net.bean.NewApkBean;
import com.dlc.beijingrfid.net.bean.NoticeNoreadsBean;
import com.dlc.beijingrfid.net.exception.ErrorMsgException;
import com.dlc.beijingrfid.net.protocol.UserProto;
import com.dlc.beijingrfid.net.protocol.base.HttpProtocol;
import com.google.gson.Gson;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by John on 2017/7/18.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {

    private static final int REQUEST_USER_INFO = 2333;

    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.iv_blur) ImageView mIvBlur;
    @BindView(R.id.iv_avatar) ImageView mIvAvatar;
    @BindView(R.id.tv_user_name) TextView mTvUserName;
    @BindView(R.id.tv_user_id) TextView mTvUserId;
    @BindView(R.id.item_feedback)
    CommonItemView mItemFeedback;
    @BindView(R.id.item_password)
    CommonItemView mItemPassword;
    @BindView(R.id.item_clear_cache)
    CommonItemView mItemClearCache;
    @BindView(R.id.item_update)
    CommonItemView mItemUpdate;
    @BindView(R.id.item_about)
    CommonItemView mItemAbout;

    private UpdateDialog updateDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews();
        loadInfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_USER_INFO) {
            // 刷新界面
            loadInfo();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        notice_noreads();
    }

    public void notice_noreads() {
        UserProto.get().notice_noreads(new HttpProtocol.Callback<NoticeNoreadsBean>() {
            @Override
            public void onSuccess(NoticeNoreadsBean noticeNoreadsBean) {
                int num = Integer.parseInt(noticeNoreadsBean.data.noreads);
                if (num > 0) {
                    mTitleBar.setRightImageBackground(R.mipmap.ling);
                }else {
                    mTitleBar.setRightImageBackground(R.mipmap.ic_news);
                }
            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {
                if (code == 0) {
                    showOneToast(getString(R.string.net_error));
                }else {
                    showOneToast(e.getMessage());
                }
            }
        });
    }
    private void loadInfo() {
        Glide.with(this)
            .load(UserHelper.get().getAvatar())
            .placeholder(R.mipmap.ic_default_avatar)
            .dontAnimate()
            .transform(new CircleTransform(getActivity()))
            .into(mIvAvatar);

        Glide.with(this)
            .load(UserHelper.get().getAvatar())
            .placeholder(R.mipmap.ic_default_avatar)
            .dontAnimate()
            .transform(new BlurTransform(getActivity()))
            .into(mIvBlur);

        mTvUserName.setText(UserHelper.get().getNickname());
        mTvUserId.setText(getString(R.string.user_id_x, "" + UserHelper.get().getAccount()));
    }

    private void initViews() {
        mTitleBar.rightImage.setOnClickListener(this);
        mIvAvatar.setOnClickListener(this);
        mItemFeedback.setOnClickListener(this);
        mItemPassword.setOnClickListener(this);
        mItemClearCache.setOnClickListener(this);
        mItemUpdate.setOnClickListener(this);
        mItemAbout.setOnClickListener(this);

        try {
            mItemClearCache.setContent(DataCleanManager.getTotalCacheSize(getActivity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        getAppVersionName(getActivity());
    }
    /**
     * 返回当前程序版本名
     */
    public  void  getAppVersionName(Context context) {
        int versioncode = 0;
        String version = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versioncode = pi.versionCode;
            version = pi.versionName;
            if (!TextUtils.isEmpty(version)){
                version = "v"+version;
                mItemUpdate.setContent(version);
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == TitleBar.RIGHT_IMAGE) {
            //  ToastUtil.showOne(getActivity(), "显示通知");
            startActivity(new Intent(getActivity(), MessageActivity.class));
        } else {
            switch (i) {
                case R.id.iv_avatar:
                    // ToastUtil.showOne(getActivity(), "设置个人资料");
                    startActivityForResult(new Intent(getActivity(), SettingActivity.class),
                        REQUEST_USER_INFO);
                    break;
                case R.id.item_feedback:
                    //  ToastUtil.showOne(getActivity(), "反馈");
                    startActivity(new Intent(getActivity(), OpinionFeedbackActivity.class));
                    break;
                case R.id.item_password:
                    Intent intent1 =new Intent(getActivity(), ForgetPasswordActivity.class);
                    intent1.putExtra("tab",1);
                    startActivity(intent1);
                    break;
                case R.id.item_clear_cache:
                    ToastUtil.showOne(getActivity(), "清理缓存");

                    try {
                        DataCleanManager.clearAllCache(getActivity());
                        mItemClearCache.setContent(DataCleanManager.getTotalCacheSize(getActivity()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.item_update:
                    update();
                    break;
                case R.id.item_about:
                    // ToastUtil.showOne(getActivity(), "关于我们");
                    startActivity(new Intent(getActivity(), AboutWeActivity.class));
                    break;
            }
        }
    }



    private void update() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<>();
       // params.put("token", UserHelper.get().getToken());

        StringBuilder sb = new StringBuilder(NetConstants.BASE_URL);
        sb.append("version")
            .append("?")
            .append("userid=")
            .append(UserHelper.get().getId())
            .append("&timestamp=")
            .append(UserHelper.get().getTimestamp())
            .append("&sign=")
            .append(UserHelper.get().getSign());

        new UpdateAppManager.Builder()
            //必须设置，当前Activity
            .setActivity(getActivity())
            //必须设置，实现httpManager接口的对象
            .setHttpManager(new UpdateAppHttpUtil())
            //必须设置，更新地址
            .setUpdateUrl(sb.toString())
            //以下设置，都是可选
            //设置请求方式，默认get
            .setPost(true)
            //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
            .setParams(params)
            //设置点击升级后，消失对话框，默认点击升级后，对话框显示下载进度
            .hideDialogOnDownloading()
            //设置头部，不设置显示默认的图片，设置图片后自动识别主色调，然后为按钮，进度条设置颜色
            .setTargetPath(path)
            //是否忽略版本
            //.showIgnoreVersion()
            .build()
            //检测是否有新版本
            .checkNewApp(new UpdateCallback() {
                /**
                 * 解析json,自定义协议
                 *
                 * @param json 服务器返回的json
                 * @return UpdateAppBean
                 */
                @Override
                protected UpdateAppBean parseJson(String json) {
                    LogPlus.e(json);
                    UpdateAppBean updateAppBean = new UpdateAppBean();
                    try {
                        Gson gson = new Gson();
                        NewApkBean newApkBean = gson.fromJson(json, NewApkBean.class);
                        if (newApkBean.code == 1) {
                            if (newApkBean.data.version.compareTo(getLocalVersionName()) > 0) {
                                updateAppBean
                                    //（必须）是否更新Yes,No
                                    .setUpdate("Yes")
                                    //（必须）新版本号，
                                    .setNewVersion(newApkBean.data.version)
                                    //（必须）更新内容
                                    .setUpdateLog("更新")
                                    //（必须）下载地址
                                    .setApkFileUrl(newApkBean.data.url)

                                    //是否强制更新，可以不设置
                                    .setConstraint(false);
                            } else {
                                showOneToast("没有新版本");
                            }
                        } else {
                            showOneToast(newApkBean.msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return updateAppBean;
                }

                /**
                 * 网络请求之前
                 */
                @Override
                public void onBefore() {
                   // showWaitingDialog("请稍后...", false);
                }

                /**
                 * 网路请求之后
                 */
                @Override
                public void onAfter() {
                    dismissWaitingDialog();
                }

                @Override
                protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                    updateDialog = new UpdateDialog(getContext(), updateApp, updateAppManager);
                    updateDialog.show();
                }
            });
    }

    @Override
    public void onDestroy() {
        if(updateDialog != null) {
            updateDialog.dismiss();
        }
        super.onDestroy();
    }

    public String getLocalVersionName() {
        String versionName = "";
        try {
            PackageInfo packageInfo = getActivity().getApplicationContext().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

}
